package com.mxin.mvvm;

import android.content.res.Resources;
import android.view.LayoutInflater;

import com.mxin.common.log.LogA;
import com.mxin.mvvm.viewmodel.BaseViewModel;
import com.mxin.ui.base.BaseActivity;
import com.mxin.util.ReflectUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

public abstract class BaseMvvmActivity<V extends ViewBinding, VM extends BaseViewModel> extends BaseActivity {

	private V mBinding;
	private VM mViewModel;

	@Override
	public void setContentView() {
		mBinding = initViewBinding();
		setContentView(mBinding.getRoot());
	}

	/**
	 * 可重写此方法，避免使用反射初始化ViewBinding，
	 * 直接调用 { ViewBinding.inflate(getLayoutInflater()) } 即可
	 *
	 * @return
	 */
	protected V initViewBinding(){
		Class<V> vClass = ReflectUtil.getSuperclass(this, 0);
		if(vClass == null){
			LogA.e(getClass().getName()+"使用反射获取ViewBinding类失败！");
			return null;
		}
		if(vClass == ViewBinding.class){
			LogA.d(getClass().getName()+"使用的是ViewBinding类,跳过使用inflate初始化布局");
			return null;
		}
		try {
			Method method = vClass.getMethod("inflate", LayoutInflater.class);
			return (V) method.invoke(null, getLayoutInflater());
		} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}


	protected V getViewBinding(){
		return mBinding;
	}

	/**
	 * 可重写此方法，避免使用反射获取ViewModel的Class
	 * 直接返回 VM.class
	 * @return
	 */
	protected Class<VM> getViewModelClass(){
		return ReflectUtil.getSuperclass(this,1);
	}

	protected VM getViewModel(){
		if(mViewModel==null){
			mViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()).create(getViewModelClass());
		}
		return mViewModel;
	}

}
